package models

import (
	"github.com/beego/beego/v2/client/orm"
	"weiboxs.com/new_h_glasses/utils"
)

type WechatSetings struct {
	Id           int64
	DepartmentId int64
	Key          string `json:"key"`
	Value        string `json:"value"`
}

func WechatSetingsTableName() string {
	return TableName("wechat_setings")
}

func (a *WechatSetings) TableName() string {
	return WechatSetingsTableName()
}

//保存数据
func (m *WechatSetings) Save() error {
	orm := orm.NewOrm();
	var se WechatSetings
	orm.QueryTable(WechatSetingsTableName()).Filter("key", m.Key).One(&se, "id");
	if se.Id >= 0 {
		m.Id = se.Id
		if _, err := orm.Update(m, "key", "value"); err != nil {
			return err
		}
	} else {
		if _, err := orm.Insert(m); err != nil {
			return err
		}
	}
	return nil
}

//获取配置信息
func (m *WechatSetings) Get() map[string]string {

	var maps []orm.Params
	if c, _ := orm.NewOrm().QueryTable(WechatSetingsTableName()).Values(&maps); c <= 0 {
		return nil
	}
	data := make(map[string]string)
	for _, m := range maps {
		data[m["Key"].(string)] = m["Value"].(string)
	}

	return data
}

//保存配置
func (m *WechatSetings) SaveSetings(data map[string]string, cur BackendUser) error {

	for k, _ := range data {
		r := WechatSetings{Key: k, Value: data[k], DepartmentId:cur.DepartmentId}
		if err := r.Save(); err != nil {
			return err
		}
	}
	return nil
}

//获取配置
func (m *WechatSetings) GetSetings(isCache bool) map[string]string {

	var data map[string]string
	var cacheID string = "wechat_config_cache"
	if err := utils.GetCache(cacheID, &data); err != nil || !isCache {
		mod := WechatSetings{}
		data = mod.Get()
		utils.SetCache(cacheID, data, 64000)
	}
	return data
}
